﻿using iTool_Cetector.Global;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace iTool_Cetector.Controllers
{
    [ApiController]
    [Route("/")]
    [Route("[controller]")]
    public class CommandController : ControllerBase
    {
        readonly GlobalStatus globalStatus;
        public CommandController(GlobalStatus globalStatus) 
        {
            this.globalStatus = globalStatus;
        }

        [HttpGet]
        public object Status()
        {
            return this.globalStatus.GetStatus();
        }

        [HttpGet("gateway")]
        public string GatewayService()
        {
            try
            {
                return GlobalUtils.GatewayUrl;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        [HttpGet("publicip")]
        public string GatewayPublicip()
        {
            try
            {
                return GlobalUtils.PublicIp;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        [HttpPost]
        public object Command(Parameter parameter)
        {
            try
            {
                return Utils.Excuter(parameter.command);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        [HttpPost("openPort")]
        public string openPost(Parameter parameter)
        {
            Utils.Logger($"shell: {Newtonsoft.Json.JsonConvert.SerializeObject(parameter)}");
            // "ufw allow 1998"
            return Utils.RunInCommandFile(parameter.command);
        }

        [HttpPost("shell")]
        public async Task<string> Shell(Parameter parameter)
        {

            Utils.Logger($"shell: {Newtonsoft.Json.JsonConvert.SerializeObject(parameter)}");

            // 数据库
            string result = await this.ExcuterDatabase(parameter);
            if (!string.IsNullOrWhiteSpace(result))
            {
                return result;
            }

            // iTool服务
            result = this.ExcuteriToolService(parameter);
            if (!string.IsNullOrWhiteSpace(result))
            {
                _ = Task.Factory.StartNew(async () =>
                {
                    await Task.Delay(4000);
                    this.globalStatus.IniInstances = false;
                });
                return result;
            }

            // Shell 指令
            return await this.ExcuterShell(parameter);
        }


        /// <summary>
        /// Shell 指令
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        private async Task<string> ExcuterShell(Parameter parameter) 
        {
            var fileName = $"/var/iTool/installs-{DateTime.Now.Millisecond}{new Random().Next(111111, 99999999)}.sh";
            try
            {
                if (System.IO.File.Exists(fileName))
                {
                    fileName = $"/var/iTool/installs-{DateTime.Now.Millisecond}{new Random().Next(111111, 99999999)}-1.sh";
                }

                System.IO.File.Create(fileName).Close();
                System.IO.File.WriteAllText(fileName, parameter.command);

                // 授权
                Utils.Excuter("chmod u+x " + fileName);
                Utils.Excuter("chmod u+x ./installiToolServer.sh");
                Utils.Excuter("chmod u+x ./installiToolConnector.sh");
                Utils.Excuter("chmod u+x ./installiToolFileCenter.sh");

                var result = Utils.Excuter("sh " + fileName);

                Utils.Logger($"shell result:{result}");

                // 结束删除文件
                System.IO.File.Delete(fileName);

                await Task.Delay(2000);
                this.globalStatus.IniInstances = false;

                return result;
            }
            catch (Exception ex)
            {
                Utils.Logger("shell", ex);

                // 结束删除文件
                System.IO.File.Delete(fileName);
                return $"Error: {ex.Message}";
            }
        }

        /// <summary>
        /// 数据库
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        private async Task<string> ExcuterDatabase(Parameter parameter) 
        {
            if (string.IsNullOrWhiteSpace(parameter.command))
            {
                if (!string.IsNullOrWhiteSpace(parameter.dbType))
                {
                    var result = await this.CreateDatabaseStructer(parameter);

                    if (!result.Item1)
                    {
                        return $"Error: {result.Item2.Message}";
                    }
                    else
                    {
                        return "数据库创建完成";
                    }
                }
            }

            return string.Empty;
        }

        /// <summary>
        /// 处理iToolProcess
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        private string ExcuteriToolService(Parameter parameter) 
        {
            var stopiToolServer = $"systemctl stop iToolServer.service";
            var stopiToolConnector = $"systemctl stop iToolConnector.service";
            //var command = $"systemctl restart iToolServer.service";
            //var command = $"systemctl restart iToolConnector.service";

            if (parameter.command == stopiToolServer)
            {
                this.WriteProcessState(iToolServiceStatusFileChange._iToolServiceProcessPath, ProcessStatusEnum.BeginStoped);
                return "进程资源释放中.";
            }
            else if (parameter.command == stopiToolConnector)
            {
                this.WriteProcessState(iToolServiceStatusFileChange._iToolConnectorProcessPath, ProcessStatusEnum.BeginStoped);
                return "进程资源释放中.";
            }
            else
            {
                return string.Empty;
            }
        }


        private async Task<(bool, Exception)> CreateDatabaseStructer(Parameter parameter) 
        {
            try
            {
                Utils.Logger($"CreateDatabaseStructer parameter: {parameter.port}-{parameter.pwd}");

                foreach (var item in parameter.dbType.Split(','))
                {
                    var check = new CheckDatabases(parameter.port, parameter.pwd, item);
                    await check.CreateDatabaseStructer();
                }

                Utils.Logger($"parameter.dbType: {parameter.dbType}");

                return (true,default);
            }
            catch (Exception ex)
            {
                Utils.Logger($"parameter.dbType Exception: {ex.Message}");
                return (false, ex);
            }
        }

        private void WriteProcessState(string path,ProcessStatusEnum processStatus)
        {
            if (!System.IO.File.Exists(path))
            {
                System.IO.File.Create(path).Close();
            }

            System.IO.File.WriteAllText(path, processStatus.ToString());
        }

    }
}
